#!/bin/sh /etc/rc.common

START=99
STOP=15

CONFIG=npc
APP_FILE=/usr/bin/npc
SERVER="npsone.cndarkhorse.top"
PORT="8686"
MACINFO=$((0x$(grep "label_macaddr" /etc/board.json |awk -F"\"" '{print $4}' | awk 'gsub(/:/,"",$0)')))

LOCK_FILE_DIR=/var/lock
LOCK_FILE=${LOCK_FILE_DIR}/${CONFIG}.lock

set_lock() {
	[ ! -d "$LOCK_FILE_DIR" ] && mkdir -p $LOCK_FILE_DIR
	exec 999>"$LOCK_FILE"
	flock -xn 999
}

unset_lock() {
	flock -u 999
	rm -rf "$LOCK_FILE"
}

unlock() {
	failcount=1
	while [ "$failcount" -le 10 ]; do
		if [ -f "$LOCK_FILE" ]; then
			let "failcount++"
			sleep 1s
			[ "$failcount" -ge 10 ] && unset_lock
		else
			break
		fi
	done
}

boot() {
	"$APP_FILE" -server="$SERVER":"$PORT" -vkey="$MACINFO" >/dev/null 2>&1 &
}

start() {
	set_lock
	"$APP_FILE" -server="$SERVER":"$PORT" -vkey="$MACINFO" >/dev/null 2>&1 &
	unset_lock
}

stop() {
	unlock
	set_lock
	killall /usr/bin/npc
	unset_lock
}

restart() {
	set_lock
	stop
	sleep 1
	start
	unset_lock
}
